package com.cqeec.gams.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqeec.gams.common.Function;
import com.cqeec.gams.dao.FunctionalModuleMapper;
import com.cqeec.gams.entity.FunctionalModule;

/**
 * 功能模块服务类。
 * 
 * @author 唐杰
 *
 */
@Service
public class FunctionalModuleServiceImpl implements FunctionalModuleService {
	@Autowired
	private FunctionalModuleMapper functionalModuleMapper;

	@Override
	public long count() {
		return functionalModuleMapper.count();
	}

	@Override
	public List<FunctionalModule> findAll() {
		return functionalModuleMapper.findAll();
	}

	@Override
	public FunctionalModule findById(String id) {
		return functionalModuleMapper.findById(id);
	}

	@Override
	public List<FunctionalModule> findPage(int pageNumber, int pageSize) {
		return functionalModuleMapper.findPage(pageNumber, pageSize);
	}

	@Override
	public void insert(FunctionalModule entity) {
		functionalModuleMapper.insert(entity);
	}

	@Override
	public void update(FunctionalModule entity) {
		functionalModuleMapper.update(entity);
	}

	@Override
	public void delete(String id) {
		functionalModuleMapper.delete(id);
	}

	@Override
	public List<FunctionalModule> getAllFunctionGroup() {
		return functionalModuleMapper.findFuncitonGroup();
	}

	@Override
	public List<Function> getFunction() {
		return convert(functionalModuleMapper.findAll());
	}

	private List<Function> convert(List<FunctionalModule> list) {
		List<Function> functions = new ArrayList<Function>();
		List<FunctionalModule> tempList = new ArrayList<FunctionalModule>();
		// 功能组
		Function f;
		for (FunctionalModule fm : list) {
			if ("1".equals(fm.getType())) {
				f = new Function();
				f.setFunctionGroup(fm);
				tempList.add(fm);
				functions.add(f);
			}
		}
		list.removeAll(tempList);
		tempList.clear();
		// 功能组的功能模块
		String fgId, fmParent;
		for (Function fun : functions) {
			fgId = fun.getFunctionGroup().getId(); // 功能组的ID
			// 在功能模块列表中查找自己的功能模块
			for (FunctionalModule fm : list) {
				fmParent=fm.getParent();
				if(fgId.equals(fmParent)) {
					fun.addFunctionalModule(fm);
					tempList.add(fm);
				}
			}
			list.removeAll(tempList);
			tempList.clear();
		}
		return functions;
	}

	@Override
	public List<Function> getRoleFunction(String roleId) {
		return convert(functionalModuleMapper.findByRole(roleId));
	}

	@Override
	public List<Function> getAccountFunction(String accountId) {
		return convert(functionalModuleMapper.findByAccount(accountId));
	}

}
